package com.sinsz.wxpn.open.message.impl;

import com.sinsz.common.exception.ApiException;
import com.sinsz.wxpn.open.BaseWxpn;
import com.sinsz.wxpn.open.message.AcceptService;
import com.sinsz.wxpn.open.support.FormaterUtils;
import com.sinsz.wxpn.properties.WxpnProperties;
import com.sinsz.wxpn.support.Constant;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 接收消息实现
 * @author chenjianbo
 * @date 2018-11-12
 */
public class AcceptServiceImpl extends BaseWxpn implements AcceptService {

    public AcceptServiceImpl(WxpnProperties prop) {
        super(prop);
    }

    @Override
    public String fetchMessage(HttpServletRequest request, String timestamp, String nonce, String signature) {
        timestamp = StringUtils.isEmpty(timestamp) ? "" : timestamp;
        nonce = StringUtils.isEmpty(nonce) ? "" : nonce;
        if (StringUtils.isEmpty(signature)) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "请求合法签名错误.");
        }
        if (StringUtils.isEmpty(super.prop().getAesToken())) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "服务器设置Token不能为空.");
        }
        List<String> list = Stream.of(timestamp, nonce, super.prop().getAesToken()).sorted().collect(Collectors.toList());
        StringBuilder buffer = new StringBuilder();
        list.forEach(buffer::append);
        if (!signature.equals(FormaterUtils.signatureSha1(buffer.toString()))) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "当前消息不是合法的请求.");
        }
        return FormaterUtils.requestBodyParams(request);
    }
}
